import React from 'react'

// 创建 Context 填入默认值（任何一个 js 变量）
const ThemeContext = React.createContext('light')

// 底层组件 - 函数组件
function ThemeLink (props) {
    // const theme = this.context // 会报错，函数组件没有实例，即 this

    return <div>
        {/* 消费 Context */}
        <ThemeContext.Consumer>
            { value => <p>link`s theme is {value}</p> }
        </ThemeContext.Consumer>
    </div>
}

// 底层组件 - class 组件
class ThemeButton extends React.Component {
    static contextType = ThemeContext  // 指定 contextType 读取当前 context
    render() {
        const theme = this.context // React 会往上找到最近的 theme
        return <div>
            <p>button`s theme is {theme}</p>
        </div>
    }
}
// ThemeButton.contextType = ThemeContext // static定义可能有兼容问题，可以用这里的方式代替

// 中间的组件再也不必指明往下传递 theme 了
function Toolbar(props) {
    return (
        <div>
            <ThemeButton/>
            <ThemeLink/>
        </div>
    )
}

class ContextDemo extends React.Component {
    constructor(props) {
        super(props)
        this.state = { theme: 'light' }
    }
    render() {
        return <div>
            <h3>Context</h3>
            {/* 生产 Context */}
            <ThemeContext.Provider value={this.state.theme}>
                <Toolbar/>
                <div>contoller`s theme is {this.state.theme}</div> <br />
                <button onClick={this.changeTheme}>chagne theme</button>
            </ThemeContext.Provider>   
        </div>
    }
    changeTheme = () => {
        this.setState({
            theme: this.state.theme === 'light' ? 'dark' : 'light'
        })
    }
}

export default ContextDemo